import json

from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.generics import CreateAPIView
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

from question.models import Label
from question.utils import get_user_dict
from users.models import User
from users.serializers.user_info import UserModelSerializer


class UserModelViewSet(ModelViewSet):
    """用户模块"""
    serializer_class = UserModelSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        """注册 ---视图集方法"""
        # 获取参数
        sms_code = request.data.pop('sms_code')
        mobile = self.request.data.get('mobile', None)

        # 连接redis数据库
        redis_conn = get_redis_connection('verify_code')
        sms = redis_conn.get(f'sms_{mobile}')

        # 短信验证码验证时效
        if not sms:
            return Response({'message': '短信验证码失效'}, status=status.HTTP_400_BAD_REQUEST)

        # 短信验证码验证
        if not sms_code == sms.decode():
            return Response({'message': '短信验证码错误'}, status=status.HTTP_400_BAD_REQUEST)

        # 反序列化对象
        serializer = self.get_serializer(data=request.data)

        # 验证数据
        serializer.is_valid(raise_exception=True)
        # 创建新用户
        user = User.objects.create_user(**request.data)

        # 状态保持
        login(request, user)

        # 构建返回数据
        redic = serializer.data

        # 创建生成token
        payload = jwt_payload_handler(user)
        redic['token'] = jwt_encode_handler(payload)

        # 获取头像信息
        redic['avatar'] = user.avatar

        # 返回数据
        return Response(redic, status=status.HTTP_201_CREATED)

    # def post(self, request, *args, **kwargs):
    #     """注册---视图方法"""
    #     # 获取验证码数据
    #     sms_code = request.data.pop('sms_code')
    #     mobile = self.request.data.get('mobile', None)
    #
    #     # 连接redis数据库
    #     redis_conn = get_redis_connection('verify_code')
    #
    #     sms = redis_conn.get(f'sms_{mobile}')
    #
    #     # 短信验证码验证时效
    #     if not sms:
    #         return JsonResponse({'success': False, 'message': '验证码过期'})
    #     # 短信验证码验证
    #     if not sms_code == sms.decode():
    #         return Response({'success': False, 'message': '验证码错误'}, status=status.HTTP_401_UNAUTHORIZED)
    #
    #     # 注册
    #     user = User.objects.create_user(**request.data)
    #
    #     payload = jwt_payload_handler(user)
    #
    #     token = jwt_encode_handler(payload)
    #     return JsonResponse({'id': user.id, 'token': token, 'avatar': user.avatar, **request.data})


# 登陆
class AuthorizationsView(CreateAPIView):

    def create(self, request, *args, **kwargs):
        # 验证用户名密码
        user = authenticate(**request.data)

        # 判断用户
        if not user:
            return Response({'message': '用户名或密码错误'}, status=status.HTTP_400_BAD_REQUEST)
        # login(request, user)
        # request.session.set_expiry(None)
        # 构建返回数据
        redic = {}

        # 创建生成token
        payload = jwt_payload_handler(user)
        redic['token'] = jwt_encode_handler(payload)

        # 状态保持
        login(request, user)

        # 获取头像信息
        redic['avatar'] = user.avatar
        redic['id'] = user.id
        redic['username'] = user.username
        redic['password'] = user.password

        # 返回数据
        return Response(redic, status=status.HTTP_201_CREATED)


# 修改个人标签
class UserLabelView(View):
    def put(self, request):
        # 获取数据
        labels = json.loads(request.body.decode())['labels']

        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        try:
            labels_obj = user.labels.all()
            # 删除
            for item in labels_obj:
                user.labels.remove(item)

            for labels_id in labels:
                label = Label.objects.get(id=labels_id)

                user.labels.add(label)

        except Exception as e:
            return JsonResponse({'message': '数据库查询错误', 'success': False})

        return JsonResponse({'message': 'ok', 'success': True})
